package com.heqiang.dao.impl;


import com.heqiang.dao.UserDao;
import com.heqiang.domain.Asign;
import com.heqiang.domain.User;
import com.heqiang.util.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class UserDaoImpl implements UserDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public User findUser(String id) {
        String sql = "select * from user where id=?";
        User user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), id);
        return user;
    }

    @Override
    public void update(User user) {
        //System.out.println(user);
        String sql = "update user set name=?,gender=?,age=?,address=?,qq=?,email=? where id=?";
        template.update(sql, user.getName(), user.getGender(), user.getAge(), user.getAddress(), user.getQq(), user.getEmail(), user.getId());
    }

    //查询总记录数
    @Override
    public int findTotalCount(String name, String address, String email) {


        String sql = "select count(*) from user where name like ? and address like ? and email like ?";
        int i=template.queryForObject(sql, Integer.class,"%" + name + "%", "%" + address + "%", "%" + email + "%");
        return i;
    }

    //查询每页数据
    @Override
    public List<User> findByPage(int start, int rows, String name, String address, String email) {
        String sql = "select * from user where name like ? and address like ? and email like ? limit ?,?";
        List<User> list = template.query(sql, new BeanPropertyRowMapper<User>(User.class), "%" + name + "%", "%" + address + "%", "%" + email + "%", start, rows);
        return list;
    }

    @Override
    public List<User> findAll() {
        //使用JDBC操作数据库...
        //1.定义sql
        String sql = "select * from user";
        List<User> users = template.query(sql, new BeanPropertyRowMapper<User>(User.class));

        return users;
    }

    @Override
    public Asign login(Asign asign) {
        //一定要注意异常处理
        try {
            String sql = "select * from asign where username = ? and password = ?";
            Asign asign1 = template.queryForObject(sql, new BeanPropertyRowMapper<Asign>(Asign.class), asign.getUsername(), asign.getPassword());
            return asign1;
        } catch (DataAccessException e) {
            //要删掉错误信息,否则一片红,吓人
        }
        return null;
    }

    @Override
    public void add(User user) {
        String sql = "insert into user values(null,?,?,?,?,?,?)";
        template.update(sql, user.getName(), user.getGender(), user.getAge(), user.getAddress(), user.getQq(), user.getEmail());
    }

    @Override
    public void del(String id) {
        //根据id删除用户
        String sql = "delete from user where id=?";
        template.update(sql, id);
    }
}
